package com.risetechnology.krystalkitchen1;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.adapter.GlossaryListAdapter;
import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.data.Glossary;
import com.risetechnology.master.NavigationActivity;

public class ActivityGlossary extends NavigationActivity {
	
	private TextView textviewGlossary;
	private TextView textviewMyGlossary;
	
	private LinearLayout layoutGlossary;
	private ListView listviewGlossary;
	private List<Glossary> allGlossaryList;
	private List<Glossary> glossaryList;
	private GlossaryListAdapter listAdapter;
	
	private EditText edittextMyGlossary;
	private LinearLayout layoutEditsAction;
	
	private EditText edittextSearchBox;

	boolean isKeyboardHide = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_glossary);
		
		// Set contents
		setContents();
	}
	
	@SuppressLint("SimpleDateFormat")
	private void setContents() {
		
		edittextSearchBox = (EditText) findViewById(R.id.et_search_box);
		edittextSearchBox.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			public void afterTextChanged(Editable s) {
				String keyword = s.toString();
				updateGlossaryList(keyword);
			}
		});
		
		edittextSearchBox.setHintTextColor(getResources().getColor(R.color.white));
		
		layoutGlossary = (LinearLayout) findViewById(R.id.ll_glossary);
		
//		final View activityRootView = findViewById(R.id.root_view);
//		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//		    @Override
//		    public void onGlobalLayout() {
//		        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
//		        if (heightDiff > 100) { 
//		        	isKeyboardHide = false;
//		        	edittextMyGlossary.setCursorVisible(true);
//		        } else {
//		        	isKeyboardHide = true;
//		        	edittextMyGlossary.setCursorVisible(false);
//		        }
//		     }
//		});
		
		layoutEditsAction = (LinearLayout) findViewById(R.id.ll_edits_action);
		
		listviewGlossary = (ListView) findViewById(R.id.lv_glossary);
		glossaryList = new ArrayList<Glossary>();
		allGlossaryList = new ArrayList<Glossary>();
		listAdapter = new GlossaryListAdapter(ActivityGlossary.this.getParent(), R.layout.list_item_glossary, glossaryList);
		listviewGlossary.setAdapter(listAdapter);
		listviewGlossary.setDivider(null);
		
		edittextMyGlossary = (EditText) findViewById(R.id.et_my_glossary);
		String savedGlossary = Shared.dbAdapter.getGlossary();
		edittextMyGlossary.setText(savedGlossary);
		edittextMyGlossary.setTypeface(Shared.font);
		edittextMyGlossary.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				edittextMyGlossary.setCursorVisible(true);
				isKeyboardHide = false;
			}
		});

		edittextMyGlossary.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
				String currentTips = edittextMyGlossary.getText().toString();
				String glossary = Shared.dbAdapter.getGlossary();
				if ((glossary == null && currentTips == null)
						|| (glossary == null && currentTips.length() == 0)) {
					layoutEditsAction.setVisibility(View.GONE);
				} else if (currentTips.equals(glossary)) {
					layoutEditsAction.setVisibility(View.GONE);
				} else {
					layoutEditsAction.setVisibility(View.VISIBLE);
				}
			}
		});
		
		textviewGlossary = (TextView) findViewById(R.id.tv_glossary);
		textviewGlossary.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewGlossary.setBackgroundColor(getResources().getColor(R.color.bg_tab_selected));
				textviewMyGlossary.setBackgroundColor(getResources().getColor(R.color.bg_tab_normal));
				
				layoutGlossary.setVisibility(View.VISIBLE);
				edittextMyGlossary.setVisibility(View.GONE);
			}
		});
		textviewMyGlossary = (TextView) findViewById(R.id.tv_my_glossary);
		textviewMyGlossary.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewGlossary.setBackgroundColor(getResources().getColor(R.color.bg_tab_normal));
				textviewMyGlossary.setBackgroundColor(getResources().getColor(R.color.bg_tab_selected));
				
				layoutGlossary.setVisibility(View.GONE);
				edittextMyGlossary.setVisibility(View.VISIBLE);
			}
		});
		
		TextView textviewSave = (TextView) findViewById(R.id.tv_save_edits);
		textviewSave.setTypeface(Shared.font);
		textviewSave.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				layoutEditsAction.setVisibility(View.GONE);
				hideKeyboard();

				edittextMyGlossary.setCursorVisible(false);

				boolean isAdded = Shared.dbAdapter.addGlossary(edittextMyGlossary.getText().toString());
				if (isAdded) {
					Toast.makeText(ActivityGlossary.this.getParent(), "My Glossary have been saved!", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(ActivityGlossary.this.getParent(), "There's error when saving glossary!", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		getGlossaryList();
	}
	
	@SuppressLint("DefaultLocale")
	private void updateGlossaryList(String keyword) {
		if (glossaryList != null) {
			glossaryList.clear();
		} else {
			glossaryList = new ArrayList<Glossary>();
		}
		
		if (allGlossaryList != null && allGlossaryList.size() > 0) {
			if (keyword != null && keyword.length() > 0) {
				int length = allGlossaryList.size();
				for (int i = 0; i < length; i++) {
					if (allGlossaryList.get(i).getTitle().toLowerCase().contains(keyword.toLowerCase())
							|| allGlossaryList.get(i).getContent().toLowerCase().contains(keyword.toLowerCase())) {
						glossaryList.add(allGlossaryList.get(i));
					}
				}
			} else {
				int length = allGlossaryList.size();
				for (int i = 0; i < length; i++) {
					glossaryList.add(allGlossaryList.get(i));
				}
			}
		}
		
		listAdapter.notifyDataSetChanged();
	}
	
	private void getGlossaryList() {
		int length = Const.GLOSSARY_TITLES.length;
		
		for (int i = 0; i < length; i++) {
			Glossary glossary = new Glossary(Const.GLOSSARY_TITLES[i], Const.GLOSSARY_CONTENTS[i]);
			glossaryList.add(glossary);
			allGlossaryList.add(glossary);
		}
		
		listAdapter.notifyDataSetChanged();
	}
	
	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edittextMyGlossary.getWindowToken(), 0);
		isKeyboardHide = true;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				if (isKeyboardHide == false) {
					hideKeyboard();
				} else {
					String myTips = Shared.dbAdapter.getGlossary();
					String currentTips = edittextMyGlossary.getText().toString();
					if (currentTips != null && !currentTips.equals(myTips)) {
						if (currentTips.length() > 0) {
							showSaveEditsDialog();
						} else {
							super.onBackPressed();
						}
					} else {
						super.onBackPressed();
					}
				}
			}
		}
		
		return false;
	}
	
	@SuppressWarnings("deprecation")
	private void showSaveEditsDialog() {
		AlertDialog dialog = new AlertDialog.Builder(ActivityGlossary.this.getParent())
		.create();
		dialog.setMessage("Save Edits to My Glossary?");

		dialog.setButton("YES", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Shared.dbAdapter.addGlossary(edittextMyGlossary.getText().toString());
				dialog.dismiss();
				layoutEditsAction.setVisibility(View.GONE);
				Toast.makeText(ActivityGlossary.this.getParent(), "My Glossary have been saved!", Toast.LENGTH_LONG).show();
			}
		});

		dialog.setButton2("NO", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				edittextMyGlossary.setText(Shared.dbAdapter.getGlossary());
				layoutEditsAction.setVisibility(View.GONE);
				Toast.makeText(ActivityGlossary.this.getParent(), "My Glossary have not been saved!", Toast.LENGTH_LONG).show();
				edittextMyGlossary.setCursorVisible(false);
			}
		});

		dialog.show();
	}
}

